package org.example.car.service.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.car.service.domain.Machine;
import org.example.car.service.listener.MachineListener;
import org.example.car.service.service.MachineService;
import org.example.car.service.utils.Result;
import org.spring.kun.common.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author: Yanyanyu
 * @Date: 2024/6/30 19:13
 */
@RequestMapping("machine")
@RestController
@CrossOrigin
public class MachineController {

    @Autowired
    private MachineService machineService;

    @RequestMapping("list")
    public Result list(@RequestBody Machine machine,@RequestParam(defaultValue = "1") Integer pageNum){
        PageHelper.startPage(pageNum,5);
        List<Machine> list=machineService.getList(machine);
        return Result.success(new PageInfo<>(list));
    }

    @RequestMapping("add")
    public Result add(@RequestBody Machine machine){
        boolean b=machineService.add(machine);
        return b?Result.success():Result.fail();
    }

    @RequestMapping("update")
    public Result update(@RequestBody Machine machine){
        boolean b=machineService.update(machine);
        return b?Result.success():Result.fail();
    }

    @RequestMapping("del")
    public Result del(Integer machineId){
        boolean b=machineService.del(machineId);
        return b?Result.success():Result.fail();
    }

    @RequestMapping("outExcel")
    public void outExcel(HttpServletResponse response){
        List<Machine> list = machineService.getList(null);
        ExcelUtils.exportExcel(list,"电机厂商","sheet",response);
    }

    @RequestMapping("readExcel")
    public void readExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Machine.class,new MachineListener(machineService)).sheet().doRead();
    }

}
